package com.anxinr.util;

import com.alibaba.fastjson.JSON;
import com.anxinr.enums.ExceptionEnum;
import com.anxinr.exception.LogicException;
import com.anxinr.pojo.dto.UserDTO;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 *
 * @author anxinr
 */
@Slf4j
@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate ;
    @Autowired
    private Executor asyncServiceExecutor ;
    /**
     * 缓存用户信息  并设置过期时间
     * @param userTokenInfo
     * @param user
     * @param minutes
     * @param userTokenInfoTime
     */
    public void setUserInfo(String userTokenInfo, UserDTO user, TimeUnit minutes, Long userTokenInfoTime) {
        redisTemplate.opsForValue().set(userTokenInfo,JSON.toJSONString(user),userTokenInfoTime,minutes) ;
    }

    /**
     * 获取登录用户信息
     * @param token
     * @return
     */
    public UserDTO getUserInfo(String token) {
        String user = redisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(user)){
            throw new LogicException(ExceptionEnum.STUDY_INVALID_LOGIN_ERROR) ;
        }
        /**重置登录时长*/
        asyncServiceExecutor.execute(()->{
            redisTemplate.opsForValue().set(token,user,60L,TimeUnit.MINUTES);
        });
        return JSON.parseObject(user, UserDTO.class);
    }

    /**
     * 发布消息
     * @author anxinr
     */
    public void sendMessage(String channel , Object data){
        redisTemplate.convertAndSend(channel,data);
    }

    /**
     * 使用   redisson 操作redis
     * redis  string
     * set  key  value
     * */
    public void setStringKeyValue(String key , String value){
        redisTemplate.opsForValue().set(key,value);
        redisTemplate.opsForValue().get(key) ;
    }

    /**
     * 使用   redisson 操作redis
     * redis  hash
     * hset  key field value
     * */
    public void setHashKeyValue(String key , String field , String value){
        redisTemplate.opsForHash().put(key,field,value);
        Object o = redisTemplate.opsForHash().get(key, field);
    }

}
